<template>
	<div class="app-container">
		<div class="filter-container">
			<div class="fr">
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" @click="handleDelete" type="danger" icon="el-icon-delete">删除</el-button> -->
      </div>
    </div>
		<el-table class="tqd_table" :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row style="width: 100%;">
			<el-table-column width="100" label="序号" show-overflow-tooltip>
        <template slot-scope="scope">
          <span @click="handleUpdate(scope.row)">{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column label="登录账号" show-overflow-tooltip prop="account">
      </el-table-column>
      <el-table-column label="别名" show-overflow-tooltip prop="nickName">
      </el-table-column>
			<el-table-column label="邮箱" show-overflow-tooltip prop="email">
      </el-table-column>
			<!-- <el-table-column label="角色" show-overflow-tooltip prop="roleList">
      </el-table-column> -->
      <el-table-column label="状态" show-overflow-tooltip prop="status">
				<template slot-scope="scope">
					<el-tag v-if="scope.row.status===0" type="success">正常</el-tag>
					<el-tag v-if="scope.row.status===1" type="danger">停用</el-tag>
				</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" @click="handlePassword(scope.row)">修改密码</el-button>
        	<el-button size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.pageNum" :page-sizes="[15,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="修改密码" :visible.sync="dialogFormSetPassword" width="450px">
      <el-form :model="ruleForm2" status-icon :rules="rules2" label-position="right" ref="ruleForm2" label-width="100px" class="demo-ruleForm">
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm2.pass" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm2.checkPass" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormSetPassword = false">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm2')">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="550px" @open="getALLRoleList">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px" style='width: 100%; '>
        <el-form-item label="登录账号" prop="account">
          <el-input v-model="temp.account"></el-input>
        </el-form-item>
        <el-form-item prop="nickName" label="别名">
					<el-input v-model="temp.nickName"></el-input>
        </el-form-item>
				<el-form-item prop="email" label="邮箱">
					<el-input v-model="temp.email"></el-input>
        </el-form-item>
        <el-form-item prop="expiryDate" label="有效时间">
          <el-date-picker v-model="temp.expiryDate" type="date" placeholder="">
    </el-date-picker>
        </el-form-item>
				<el-form-item prop="roleIdList" label="角色">
					<el-select v-model="temp.roleIdList" multiple style='width: 100%; ' placeholder="请选择" @change="updateDatadd">
						<el-option v-for="item in allRoles" :key="item.id" :label="item.roleName" :value="item.id.toString()">
						</el-option>
					</el-select>
        </el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="temp.status">
						<el-radio :label="0">正常</el-radio>
						<el-radio :label="1">停用</el-radio>
					</el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
	</div>
</template>
<script>
import { saveUser, updateUser, getUserInfo, getUserList, deleteUser, resetPasword } from '@/api/user'
import { getALLRoleList } from '@/api/role'
import waves from '@/directive/waves' // 水波纹指令
import { showMsg } from '@/utils'
export default {
  name: 'complexTable',
  directives: {
    waves
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm2.checkPass !== '') {
          this.$refs.ruleForm2.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm2.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 15
      },
      temp: {
        id: undefined,
        nickName: null,
        password: null,
        account: null,
        email: null,
        avatar: null,
        roleIdList: [],
        status: 0,
        expiryDate: null
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      dialogFormSetPassword: false,
      rules: {
        account: [{ required: true, message: '必填', trigger: 'blur' }],
        nickName: [{ required: true, message: '必填', trigger: 'blur' }],
        expiryDate: [{ required: true, message: '请选择有效时间', trigger: 'change' }],
        roleIdList: [{ required: true, message: '至少选择一个角色', trigger: 'change' }]
      },
      downloadLoading: false,
      allRoles: null,
      ruleForm2: {
        id: null,
        pass: '',
        checkPass: ''
      },
      rules2: {
        pass: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {

  },
  methods: {
    getALLRoleList() {
      getALLRoleList().then(response => {
        this.allRoles = response.data.data
      })
    },
    updateDatadd() {
      this.$forceUpdate()
    },
    getList() {
      this.listLoading = true
      getUserList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
        // for (var item of this.list) {
        //   if (item.roleList === null) {
        //     item.roleList = []
        //   }
        // }
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    handleDelete(row) {
      this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var roleIds = [row.id]
        deleteUser(roleIds).then(res => {
          if (res.data.code === 0) {
            showMsg(res.data.message, 1)
            this.getList()
          } else {
            showMsg(res.data.message, 2)
          }
        })
      }).catch(() => {
        // console.log('===')
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        nickName: null,
        account: null,
        email: null,
        avatar: null,
        roleIdList: [],
        password: null,
        status: 0,
        expiryDate: null
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveUser(this.temp).then(res => {
            if (res.data.code === 0) {
              this.dialogFormVisible = false
              showMsg(res.data.message, 1)
              this.getList()
            } else {
              showMsg(res.data.message, 2)
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.resetTemp()
      getUserInfo(row.id).then(response => {
        this.temp = Object.assign({}, response.data.data) // copy obj
        this.temp.roleIdList = this.temp.roleList
        // console.log(this.temp.roleIdList === null)
        // if (this.temp.roleIdList === null) {
        //   this.temp.roleIdList = []
        // }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUser(tempData).then(res => {
            if (res.data.code === 0) {
              this.dialogFormVisible = false
              showMsg(res.data.message, 1)
              this.getList()
            } else {
              showMsg(res.data.message, 2)
            }
          })
        }
      })
    },
    handlePassword(row) {
      this.dialogFormSetPassword = true
      this.ruleForm2.id = row.id
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var obj = {
            userId: this.ruleForm2.id,
            password: this.ruleForm2.pass

          }
          resetPasword(obj).then(res => {
            this.dialogFormSetPassword = false
            if (res.data.code === 0) {
              this.dialogFormVisible = false
              showMsg(res.data.message, 1)
              this.getList()
              this.resetForm(formName)
            } else {
              showMsg(res.data.message, 2)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
    // handleDelete(row) {
    //   this.$prompt('请输入密码', '确认删除？', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消'
    //     // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
    //     // inputErrorMessage: '邮箱格式不正确'
    //   }).then(({ value }) => {
    //     this.$message({
    //       type: 'success',
    //       message: '你的密码是: ' + value
    //     })
    //   }).catch(() => {
    //     this.$message({
    //       type: 'info',
    //       message: '取消输入'
    //     })
    //   })
    // }
  }
}
</script>